package com.hy.ratelimiting.limiting;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:
 * <p>
 * User:Mr.Du
 * Date:2024/4/25
 * Time:10:59
 */
@Slf4j
@Service
public class FixedWindowRateLimiter {

    private final AtomicInteger counter = new AtomicInteger(0);
    private volatile long lastRequestTime;
    private long windowUnit = 1000L;
    private int threshold = 4;

    public FixedWindowRateLimiter(){}

    public FixedWindowRateLimiter(long windowUnit, int threshold) {
        this.windowUnit = windowUnit;
        this.threshold = threshold;
    }

    public boolean allowRequest() {
        long currentTime = System.currentTimeMillis();
        if (currentTime - lastRequestTime > windowUnit) {
            counter.set(0);
            lastRequestTime = currentTime;
        }
        if (counter.get() < threshold) {
            counter.incrementAndGet();
            return true;
        }
        return false;
    }

//    private volatile int limit = 6; // 限制的请求数量
//    private volatile long windowSize = 1000; // 时间窗口的大小，以毫秒为单位
//    private volatile long lastRequestTime; // 时间窗口的大小，以毫秒为单位
//    private volatile long count;
//
//
//    public synchronized boolean allowRequest() {
//        long currentTime = System.currentTimeMillis();
//        if(currentTime - lastRequestTime > windowSize){
//            count = 0;
//            lastRequestTime = currentTime;
//        }
//
//        if(count < limit){
//            count= count + 1;
//            return true;
//        }
//        return false;
//
//    }
}
